package cn.gov.msa.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;

import cn.gov.msa.model.Dictionary;
import cn.gov.msa.model.DictionaryDetail;
import cn.gov.msa.model.File;
import cn.gov.msa.model.Notice;
import cn.gov.msa.model.UserDetail;
import cn.gov.msa.service.NoticeService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
@RequestMapping(value = "/notice", produces = "text/plain;charset=UTF-8")
public class NoticeController {

	ObjectMapper mapper = new ObjectMapper();

	@Autowired
	private NoticeService noticeService;

	@RequestMapping(value = "/list")
	public String list(@RequestBody JSONObject params, HttpSession session) throws Exception {
		String result = "";
		int pageNum = 1;
		int pageSize = 10;
		if (params.has("pageNum")) {
			pageNum = params.getInt("pageNum");
			params.remove("pageNum");
		}
		if (params.has("pageSize")) {
			pageSize = params.getInt("pageSize");
			params.remove("pageSize");
		}
		System.out.println("list:"+ params);
		if("".equals(params.optString("orgCode"))){
			UserDetail userDetail=(UserDetail) session.getAttribute("userDetail");
			params.put("orgCode", userDetail.getOrgcode());
		}
		Notice notice = mapper.readValue(params.toString(), Notice.class);
		List<Notice> noticeList = noticeService.selectNotice(pageNum, pageSize, notice);
		JSONArray ja = new JSONArray();
		for (Notice notice2 : noticeList) {
			JSONObject json = new JSONObject();
			json.put("noticeId", notice2.getNoticeId());
			json.put("title", notice2.getTitle());
			json.put("symbol", notice2.getSymbol());
			json.put("orgCode", notice2.getOrgCode());
			json.put("contents", notice2.getContents());
			json.put("range", notice2.getRange());
			json.put("contents", notice2.getContents());
			json.put("orgName", notice2.getOrgName());
			json.put("top", notice2.getTop());
			json.put("theme", notice2.getTheme());
			json.put("label", notice2.getLabel());
			json.put("fileId", notice2.getFileId());
			json.put("evaluation", notice2.getEvaluation());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String str = sdf.format(notice2.getPublishTime());
			json.put("publishTime", str);
			str = sdf.format(notice2.getAsofDate());
			json.put("asofDate", str);
			if (notice2.getFailDate() != null) {
				str = sdf.format(notice2.getFailDate());
				json.put("failDate", str);
			}
			ja.add(json);
		}
		// 获取分页信息
		PageInfo page = new PageInfo(noticeList);
		JSONObject jsonResult = new JSONObject();
		jsonResult.put("total", page.getTotal());
		jsonResult.put("rows", ja);
		result = jsonResult.toString();
		return result;
	}

	@RequestMapping(value = "/save", produces = "text/html;charset=UTF-8")
	public String save(@RequestBody JSONObject param) throws Exception {
		int result = 0;
		String info = "";
		boolean save = false;
		// 得到类型的model数据
		Notice notice = mapper.readValue(param.toString(), Notice.class);
		if (notice.getNoticeId() != null && !notice.getNoticeId().equals("")) {
			save = noticeService.updateNotice(notice);
		} else {
			save = noticeService.saveData(notice);
		}
		JSONObject jsonResult = new JSONObject();
		if (save) {
			result = 1;
			info = "数据保存成功！";
		} else {
			result = 0;
			info = "数据保存失败！";
		}
		jsonResult.put("fileId", notice.getFileId());
		jsonResult.put("result", result);
		jsonResult.put("info", info);
		jsonResult.put("noticeId", notice.getNoticeId());
		return jsonResult.toString();
	}

	@RequestMapping(value = "/delete")
	public String delete(String noticeId) throws Exception {
		int result = 0;
		String info = "";
		JSONArray japaram = new JSONArray();
		try {
			JSONObject param = new JSONObject();
			param.put("noticeId", noticeId);
			japaram.add(param);
			int delete = noticeService.deleteNotice(noticeId);
			result = delete > 0 ? 1 : 0;
			info = delete > 0 ? "删除成功！" : "删除失败！";
		} catch (Exception e) {
			result = 2;
			info = "删除异常!";
		}
		JSONObject jsonResult = new JSONObject();
		jsonResult.put("result", result);
		jsonResult.put("info", info);
		jsonResult.put("datas", japaram);
		return jsonResult.toString();
	}

	@RequestMapping(value = "/batchDelete")
	public String batchDelete(String noticecodes) throws Exception {
		int result = 0;
		String info = "";
		JSONArray japaram = new JSONArray();
		int delete = 0;
		try {
			String dictcodeResult = "";
			for (int i = 0; i < noticecodes.split(",").length; i++) {
				String noticecode = noticecodes.split(",")[i];
				noticeService.deleteNotice(noticecode);
				delete++;
			}
			result = delete > 0 ? 1 : 0;
			info = delete > 0 ? "批量删除成功！" : "批量删除失败！";
		} catch (Exception e) {
			result = 2;
			info = "删除异常!";
		}
		JSONObject jsonResult = new JSONObject();
		jsonResult.put("result", result);
		jsonResult.put("info", info);
		return jsonResult.toString();
	}

	@RequestMapping(value = "/fileId")
	public void upload(String noticeId, String fileId) throws Exception {
		Notice notice = new Notice();
		notice.setNoticeId(noticeId);
		notice.setFileId(fileId);
		noticeService.updateNoticeFileId(notice);
	}

	@RequestMapping(value = "/getFileUrl")
	public String getFileUrl(String fileId) throws Exception {
		String result = "";
		List<File> fileUrl = new ArrayList<>();
		JSONObject jsonResult = new JSONObject();
		if (fileId == null) {
			jsonResult.put("result", "0");
		} else {
			String[] files = fileId.split(",");
			for (int i = 0; i < files.length; i++) {
				File file = noticeService.selectFile(files[i]);
				fileUrl.add(file);
			}
			jsonResult.put("result", "1");
			jsonResult.put("file", fileUrl.toArray());
		}
		result = jsonResult.toString();
		return result;
	}

	@RequestMapping(value = "/deleteFile.do")
	public String deleteFile(String key, String noticeId) {
		Notice notice = new Notice();
		notice.setNoticeId(noticeId);
		Notice notice1 = noticeService.selectNotice(1, 1, notice).get(0);
		String fileids = notice1.getFileId();
		int index = fileids.indexOf(",");
		if (index == -1) {
			notice.setFileId("");
		} else {
			String[] arg = notice1.getFileId().split(",");
			String fileId = "";
			for (int i = 0; i < arg.length; i++) {
				if (!arg[i].equals(key)) {
					fileId += arg[i] + ",";
				}
			}
			fileId = fileId.substring(0, fileId.length() - 1);
			notice.setFileId(fileId);
		}
		noticeService.updateNoticeFileId(notice);
		return "[]";
	}
}
